package com.dqp.cslggroup.School;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import com.bumptech.glide.Glide;
import com.dqp.cslggroup.ConnectSever.Accept;
import com.dqp.cslggroup.ConnectSever.Send;
import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.R;
import com.dqp.cslggroup.UI.BaseActivity;
import com.dqp.cslggroup.UI.ClubMoreAdapter;
import com.dqp.cslggroup.UI.MyApplication;
import com.dqp.cslggroup.Util.Comment;
import com.dqp.cslggroup.Util.ToastUtil;
import com.dqp.cslggroup.bean.student;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class Talk_more extends BaseActivity implements AbsListView.OnScrollListener {
    private ListView listView;
    private String[] strings;
    private int[] ints;
    private ArrayList<Comment> dataList;
    private TextView fine, bad, comment;
    private Comment comments = new Comment();
    private boolean flag = true;
    public View loadmoreView;
    public LayoutInflater inflater;
    public int last_index;
    public int first_index;
    public int total_index;
    public boolean isLoading = false, showMore = true, report = true, delete = true;//表示是否正处于加载状态
    private int count = 1;
    private ClubMoreAdapter clubMoreAdapter;
    private LinearLayout head;

    @SuppressLint("InflateParams")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.talk_more);
        EventBus.getDefault().register(this);
        Toolbar toolbar = findViewById(R.id.talk_toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        Intent intent = getIntent();
        head = findViewById(R.id.list_head);
        strings = intent.getStringArrayExtra("string");
        ints = intent.getIntArrayExtra("int");
        inflater = LayoutInflater.from(this);
        loadmoreView = inflater.inflate(R.layout.bottom, null);//获得刷新视图
        loadmoreView.setVisibility(View.GONE);//设置刷新视图默认情况下是不可见的
        listView = findViewById(R.id.talk_list);
        listView.setOnScrollListener(this);
        listView.addFooterView(loadmoreView, null, false);
        initCard();
        initCommentList();
        initDelete();
    }

    public void initDelete() {
        ImageButton imageButton = findViewById(R.id.talk_toolbar_add);
        imageButton.setOnClickListener(v -> {
            if (student()) {
                final com.dqp.cslggroup.UI.AlertDialog alertDialog = new com.dqp.cslggroup.UI.AlertDialog(Talk_more.this);
                alertDialog.builder();
                alertDialog.setGone()
                        .setTitle("删除or举报")
                        .setMsg("请选择您对此说说的操作")
                        .setNegativeButton("删除", R.color.colorAccent, v1 -> new Thread(() -> {
                            if (delete) {
                                if (delete && Send.deleteTalk(comments.getSno(), ints[0], "delete")) {
                                    delete = false;
                                    ToastUtil.showToast("删除申请已提交！");
                                } else ToastUtil.showToast("提交失败！");
                            } else ToastUtil.showToast("请勿重复提交！");
                        }).start())
                        .setPositiveButton("举报", R.color.colorAccent, v2 -> new Thread(() -> {
                            if (report) {
                                if (Send.deleteTalk(comments.getSno(), ints[0], "report")) {
                                    report = false;
                                    ToastUtil.showToast("举报已提交！");
                                } else ToastUtil.showToast("提交失败！");
                            } else ToastUtil.showToast("请勿重复提交！");
                        }).start()).show();
            } else ToastUtil.showToast("请先完成登录！");
        });


    }

    @SuppressLint({"SetTextI18n", "HandlerLeak"})
    public void initCard() {
        TextView date = findViewById(R.id.club_date);
        date.setVisibility(View.VISIBLE);
        date.setText(strings[3]);
        ImageView club_head = findViewById(R.id.club_hade);
        club_head.setVisibility(View.GONE);
        ImageView imageView = findViewById(R.id.talk_hade);
        imageView.setVisibility(View.VISIBLE);
        if (strings[2] != null && strings[2].length() > 10) {
            ImageView talk_img = findViewById(R.id.talk_img);
            talk_img.setVisibility(View.VISIBLE);
            Glide.with(Talk_more.this).load(strings[2]).into(talk_img);
        }
        if (strings.length >= 6 && strings[4] != null && strings[4].length() > 10)
            Glide.with(Talk_more.this).load(strings[4]).into(imageView);
        else if (strings.length >= 6 && strings[5] != null && strings[5].equals("男")) {
            Drawable drawable = ContextCompat.getDrawable(Talk_more.this, R.drawable.strangerm);
            imageView.setBackground(drawable);
        } else if (strings.length >= 6 && strings[5] != null && strings[5].equals("女")) {
            Drawable drawable = ContextCompat.getDrawable(Talk_more.this, R.drawable.strangerw);
            imageView.setBackground(drawable);
        } else {
            Drawable drawable = ContextCompat.getDrawable(Talk_more.this, R.drawable.stranger);
            imageView.setBackground(drawable);
        }
        TextView name = findViewById(R.id.club_name);
        TextView des = findViewById(R.id.club_des);
        des.setTextSize(14);
        des.setSingleLine(false);
        fine = findViewById(R.id.club_fine);
        bad = findViewById(R.id.club_bad);
        comment = findViewById(R.id.club_comment);
        LinearLayout fine_lin = findViewById(R.id.club_fine_lin);
        LinearLayout bad_lin = findViewById(R.id.club_bad_lin);
        LinearLayout comment_lin = findViewById(R.id.club_comment_lin);
        if (strings.length >= 4) {
            name.setText(strings[0]);
            des.setText(strings[1]);
        }

        if (ints.length >= 4) {
            fine.setText(ints[1] + "");
            bad.setText(ints[2] + "");
            comment.setText(ints[3] + "");
        }

        fine_lin.setOnClickListener(v -> new Thread(() -> {
            if (flag) {
                if (Send.talkZan(ints[0] + "", "fine")) {
                    flag = false;
                    EventBus.getDefault().post(new MessageEvent("Talk_more", 2, null));
                } else {
                    EventBus.getDefault().post(new MessageEvent("Talk_more", 5, 1));
                }
            }
        }).start());

        bad_lin.setOnClickListener(v -> new Thread(() -> {
            if (flag) {
                if (Send.talkZan(ints[0] + "", "bad")) {
                    flag = false;
                    EventBus.getDefault().post(new MessageEvent("Talk_more", 3, null));

                } else {
                    EventBus.getDefault().post(new MessageEvent("Talk_more", 5, 2));
                }
            }
        }).start());
        comment_lin.setOnClickListener(v -> comment());
    }

    public void comment() {
        if (student()) {
            final android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(Talk_more.this);
            @SuppressLint("InflateParams") View view = LayoutInflater.from(Talk_more.this).inflate(R.layout.comment_edit, null);
            builder.setView(view);
            final EditText content = view.findViewById(R.id.comment_editview);
            TextView put = view.findViewById(R.id.comment_editBtn);
            Dialog dialog = builder.show();
            put.setOnClickListener(view1 -> {
                String contents = content.getText().toString();
                if (contents.length() > 0) {
                    comments.setContent(contents);
                    new Thread(() -> {
                        if (Send.putTalkComment(comments, ints[0] + "")) {
                            dialog.dismiss();
                            EventBus.getDefault().post(new MessageEvent("Talk_more", 4, null));
                        } else {
                            EventBus.getDefault().post(new MessageEvent("Talk_more", 5, 3));
                        }
                    }).start();
                } else dialog.dismiss();
            });
        } else ToastUtil.showToast("登陆后才可评论！");
    }


    @SuppressLint({"SetTextI18n", "HandlerLeak"})
    private void initCommentList() {
        new Thread(() -> {
            ArrayList<Comment> dataList = Accept.getTalkComment(ints[0] + "", count);
            EventBus.getDefault().post(new MessageEvent("Talk_more", 1, dataList));
        }).start();
    }


    @SuppressLint("HandlerLeak")
    private boolean student() {
        List<student> studentList = MyApplication.getDaoInstant().getStudentDao().loadAll();
        if (studentList.size() > 0) {
            student student = studentList.get(0);
            String xh = student.getXh();
            String xm = student.getXm();
            String xb = student.getXb();
            String xy = student.getXy();
            comments.setComment_name(xm);
            comments.setCollege(xy);
            comments.setGender(xb);
            comments.setSno(xh);
            return true;
        }
        return false;
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        last_index = firstVisibleItem + visibleItemCount;
        first_index = firstVisibleItem;
        total_index = totalItemCount;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (last_index == total_index && (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE)) //表示此时需要显示刷新视图界面进行新数据的加载(要等滑动停止)
        {
            if (!isLoading && showMore) {
                isLoading = true;  //不处于加载状态的话对其进行加载
                loadmoreView.setVisibility(View.VISIBLE);    //设置刷新界面可见
                onLoad();
            }
        }
    }

    /**
     * 刷新加载
     */
    public void onLoad() {
        // 加载完毕
        count++;
        new Thread(() -> {
            ArrayList<Comment> addDataList = Accept.getTalkComment(ints[0] + "", count);
            if (addDataList.size() == 0) {
                showMore = false;
                count--;
            } else dataList.addAll(addDataList);
            EventBus.getDefault().post(new MessageEvent("Talk_more", 6, null));
        }).start();

    }

    /**
     * 加载完成
     */
    public void loadComplete() {

        loadmoreView.setVisibility(View.GONE);//设置刷新界面不可见
        isLoading = false;//设置正在刷新标志位false
        Talk_more.this.invalidateOptionsMenu();
        listView.removeFooterView(loadmoreView);//如果是最后一页的话，则将其从ListView中移出
    }

    /**
     * 加载完成
     */
    public void showBottom_line() {
        if (!showMore) {
            @SuppressLint("InflateParams") View bottom_line = inflater.inflate(R.layout.bottom_line, null);//获得刷新视图
            bottom_line.setVisibility(View.VISIBLE);//设置刷新视图默认情况下是不可见的
            listView.addFooterView(bottom_line);
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals("Talk_more")) {
            switch (event.getWhat()) {
                case 1:
                    dataList = (ArrayList<Comment>) event.getObj();
                    clubMoreAdapter = new ClubMoreAdapter(dataList, Talk_more.this);
                    listView.setAdapter(clubMoreAdapter);
                    head.setVisibility(View.GONE);
                    break;
                case 2:
                    ints[1]++;
                    fine.setText(ints[1] + "");
                    break;
                case 3:
                    ints[2]++;
                    bad.setText(ints[2] + "");
                    break;
                case 4:
                    ints[3]++;
                    comment.setText(ints[3] + "");
                    count = 1;
                    initCommentList();
                    break;
                case 5:
                    String s = null;
                    if (event.getZhou() == 1)
                        s = "点赞";
                    if (event.getZhou() == 2)
                        s = "吐槽";
                    if (event.getZhou() == 3)
                        s = "评论";
                    ToastUtil.showToast(s + "失败！");
                    break;
                case 6:
                    if (showMore)
                        clubMoreAdapter.notifyDataSetChanged();
                    loadComplete();//刷新结束
                    showBottom_line();
                    break;
            }
        }
    }


}
